package org.passeg;

import org.mg.engine.Instruct;
import org.mg.engine.InstructFactory;
import org.msg.commons.InstructUtils;

import java.io.*;
import java.net.Socket;

/**
 * Create by bo.chen in 2018/10/9 0:21
 */
public class MgSession extends SessionAbstract {

    public MgSession(Socket socket) {
        this.socket = socket;
        this.init();
    }

    private void init() {
        try {
            listen();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Socket getSocket() {
        return this.socket;
    }

    @Override
    public void println(String message) throws IOException {
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.println(message);
    }

    @Override
    public String listen() throws IOException {
        while(true){
            String message = new BufferedReader(new InputStreamReader(socket.getInputStream())).readLine();
            String cmd = InstructUtils.getInstruct(message);
            Instruct instruct = InstructFactory.getBean(cmd);
            String params = InstructUtils.getParams(message);
            instruct.init(this).execute(params);
        }
    }
}
